#include "framecombobox.h"

#include <QPainter>
#include <QTextDocument>
#include <QAbstractTextDocumentLayout>
#include <QAbstractItemView>

FrameComboBoxItemDelegate::FrameComboBoxItemDelegate( QObject *aParent ) : QItemDelegate( aParent )
{

}

QSize FrameComboBoxItemDelegate::sizeHint( const QStyleOptionViewItem &aOption, const QModelIndex &aIndex ) const
{
    return QSize( 78 + 250, 73 );
}

void FrameComboBoxItemDelegate::drawFocus( QPainter *aPainter, const QStyleOptionViewItem &aOption, const QRect &aRect ) const
{
    Q_UNUSED( aPainter );
    Q_UNUSED( aOption );
    Q_UNUSED( aRect );
}

void FrameComboBoxItemDelegate::paint( QPainter *aPainter, const QStyleOptionViewItem &aOption, const QModelIndex &aIndex ) const
{
    QItemDelegate::paint( aPainter, aOption, aIndex );
    QRect rect = aOption.rect;
    rect.setX( 78 + 1 );
    aPainter->fillRect( rect, ( aOption.state.testFlag( QStyle::State_Selected ) ) ? aOption.palette.color( QPalette::Highlight ) : Qt::white );
    aPainter->save();
    QTextDocument doc;
    QColor c = ( aOption.state.testFlag( QStyle::State_Selected ) ) ? aOption.palette.color( QPalette::HighlightedText ) : aOption.palette.color( QPalette::Text );
    QString str;
    str.append( "<table><td><font color=""" + c.name() + """>" );
    str.append( "<b>" + aIndex.data( Qt::DisplayRole ).toString() + "</b>" );
    str.append( "</td><tr>" );
    str.append( "<td><font color=""" + c.name() + """><center>Author: " + aIndex.data( FrameComboBox::cAuthorRole ).toString() + "</center></td>" );
    str.append( "</table>" );
    doc.setHtml( str );
    aPainter->translate( rect.x() + 10, rect.y() + 15 );
    QAbstractTextDocumentLayout::PaintContext context;
    doc.setPageSize( rect.size()*=8 );
    doc.documentLayout()->draw( aPainter, context );
    aPainter->restore();
}


FrameComboBox::FrameComboBox( QWidget *aParent ) : KComboBox( aParent )
{
    view()->setIconSize( QSize( 78, 63 ) );
    view()->setMinimumWidth( 300 );
    setItemDelegate( new FrameComboBoxItemDelegate( this ) );
}

void FrameComboBox::setPlugins( const QList<KPluginInfo> &aList )
{
    clear();
    foreach( KPluginInfo info, aList )
    {
        addItem( info.name() );
        //setItemData( pDecorationCombo->count() - 1, gKDCFrameGenerator->preview( info.name() ), Qt::DecorationRole );
        setItemData( count() - 1, info.author(), FrameComboBox::cAuthorRole );
    }
}
